import {Component, ViewEncapsulation, Input} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {UserService} from '../../services/app.user';
import {AuthenticationHelper} from "../../app.authentication";
import {Router} from '@angular/router';
import {BaThemeSpinner}  from '../../theme/services';
import {Constants} from '../../../app/common/app.constants'
import {EmailValidator} from "../../theme/validators/email.validator";
declare const FB:any;
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'login',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./login.scss'],
    templateUrl: './login.html',
})

export class Login {
    @Input()
    constants:Constants;
    form:FormGroup;
    submitted:boolean = false;
    userInfo:any;
    loginError:string = "";
    start:any;
    end:any;
    check:any;

    constructor(fb:FormBuilder, private userService:UserService, private router:Router, private authentication:AuthenticationHelper, private spinner:BaThemeSpinner) {
        this.constants = new Constants();
        toastr.options = {positionClass: 'toast-top-right',};
        this.form = fb.group({
            'email': ['', Validators.compose([Validators.required, Validators.minLength(4), EmailValidator.validate])],
            'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
        });

        // Function call reset FB
        this.resetFB();
        this.start = 0;
        this.check = 0;
        // Function for call timeline start count
        this.startCount();
    }

    // Function call for login
    onSubmit(values) {
        this.spinner.showProgress();
        this.submitted = true;
        if (this.form.valid) {
            let data = {
                username: values.email,
                password: values.password
            };
            this.userService.userLogin(data).subscribe(
                data => this.loginSucces(data),
                error => this.loginFail(error)
            );
        }
    }

    // Function call after login successfully
    loginSucces(result) {
        toastr.success(this.constants.LOGINSUCCESS);
        this.authentication.setLoggedIn(result.token);
        this.authentication.setUser(result.user);
        this.router.navigate(['dashboard']);
        this.spinner.hideProgress();
        this.closeTimelineCount();

    }

    // Function call if login failed
    loginFail(error) {
        this.spinner.hideProgress();
        console.log(error,'-----------------');
        
        toastr.error(error.error_message);
        this.submitted = false;
        this.loginError = error.error_message;
    }

    // Function for facebook login
    onFacebookLoginClick() {
        FB.login(
            (response) => {
                this.statusChangeCallback(response);

            }, {scope: 'email', return_scopes: true}
        );
    }

    // Function for send facebook data to server
    statusChangeCallback(resp) {
        if (resp.status === 'connected') {
            let self = this;
            FB.api('/me?fields=id,name,email,first_name,last_name,gender,picture.width(150).height(150),age_range,friends',
                function (result) {
                    if (result && !result.error) {
                        self.userInfo = result;
                        self.userInfo.token = resp.authResponse.accessToken;
                        self.userService.facebookLogin(self.userInfo).subscribe(
                            data => self.loginSucces(data),
                            error => self.loginFail(error)
                        );

                    }
                });

        } else if (resp.status === 'not_authorized') {
            this.resetFB();
            toastr.error(this.constants.FBERROR);
        } else {
            this.resetFB();
            toastr.error(this.constants.FBALERT);
        }
    }

    // Function for reset facebook
    resetFB() {
        FB.init({
            appId: '1766419320344890',
            cookie: true,
            xfbml: true,
            version: 'v2.8'
        });
    }

    // timer function start count of timeline
    timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1000);
    }

    // To function for start timstamp count
    startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    public closeTimelineCount() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
        let seq = {
          sequence: {
            "pageName": 'login',
            "timeSpent": this.start
          },
          "totalTime" : this.start
        };
        this.userService.setUrlSeq(seq).subscribe();
    }
}
